<template>
  <div>
    <h1> <img alt="Vue logo" src="@/assets/logo.png" width="24px" height="24px">TinyMCE VUE开始示例</h1>
    <!--  文档地址  https://www.tiny.cloud/docs/integrations/vue/#tinymce-script-src -->
    <Editor
        tinymce-script-src="./tinymce/tinymce.js"
        :init="setting" v-model="contentValue"/>
    <button @click="displayPreview">展示</button>
    <h1>以下是展示</h1>
    <div>
      <iframe sandbox="allow-scripts allow-same-origin" style="width:500px; height:450px;border:none" data-alloy-tabstop="true" tabindex="-1"
              :srcdoc="srcdoc">
      </iframe>
    </div>
  </div>
</template>

<script>
import Editor from '@tinymce/tinymce-vue'
import fileApi from '@/api/file'
const contentCss=`
img.img_default {
    max-width: 100%;
    height: fit-content;
}

img.img_green_border {
    border: 4px solid green;
}

img.img_blue_border {
    border: 4px solid blue;
}

img.img_red_border {
    border: 4px solid red;
}
`

export default {
  components:{
    Editor
  },
  name: 'tinymceDemo',
  data:()=>{
    return {
      setting:{
        language: 'zh_CN',
        height: 650, //编辑器高度
        min_height: 400,
        /*content_css: [ //可设置编辑区内容展示的css，谨慎使用
            '/static/reset.css',
            '/static/ax.css',
            '/static/css.css',
        ],*/
        content_style: contentCss,
        fontsize_formats: '12px 14px 16px 18px 24px 36px 48px 56px 72px',
        font_formats: '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;',
        link_list: [],
        image_class_list: [
          {title: '默认', value: 'img_default'},
          {
            title: '边框',
            menu: [
              {title: '绿色边框', value: 'img_green_border'},
              {title: '蓝色边框', value: 'img_blue_border'},
              {title: '红色边框', value: 'img_red_border'}
            ]
          }
        ],
        importcss_append: true,
        toolbar_sticky: true,
        autosave_ask_before_unload: false,
        plugins: 'importword powerpaste print preview searchreplace autolink directionality visualblocks visualchars ' +
            'fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking ' +
            'anchor insertdatetime advlist lists wordcount imagetools textpattern help emoticons ' +
            'autosave indent2em autoresize importcss',
        toolbar: 'code undo redo restoredraft importword | cut copy paste pastetext | \
        forecolor backcolor bold italic underline strikethrough link anchor | \
        alignleft aligncenter alignright alignjustify outdent indent | \
        styleselect formatselect fontselect fontsizeselect | bullist numlist | \
        blockquote subscript superscript removeformat | \
        table image media charmap emoticons hr pagebreak insertdatetime print preview |\
         fullscreen | indent2em lineheight',
        file_picker_callback: function (callback, value, meta) {
          var filetype = '.pdf, .txt, .zip, .rar, .7z, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .mp3, .mp4';
          //后端接收上传文件的地址
          //为不同插件指定文件类型及后端地址
          switch (meta.filetype) {
            case 'image':
              filetype = '.jpg, .jpeg, .png, .gif';
              break;
            case 'media':
              filetype = '.mp3, .mp4';
              break;
            case 'file':
            default:
          }
          //模拟出一个input用于添加本地文件
          var input = document.createElement('input');
          input.setAttribute('type', 'file');
          input.setAttribute('accept', filetype);
          input.click();
          input.onchange = function () {
            var file = this.files[0];
            fileApi.uploadFile(file).then(location=>{
              if (meta.filetype === 'file') {
                //第一个参数是可访问的图片url路径
                callback(location, {classes: [], text: file.name});
              }
              if (meta.filetype === 'image') {
                callback(location, {alt: file.name});
              }
              if (meta.filetype === 'media') {
                callback(location);
              }
            }).catch(msg=>{
              throw new Error(msg);
            })
          }
        },
        images_upload_handler: function (blobInfo, callback, failFun, progress) {
          var file = new File([blobInfo.blob()], blobInfo.filename());
          fileApi.uploadFile(file,progress)
              .then(location=>{
            callback(location, {alt: file.name, classes: []});
          }).catch(failFun)
        }
      },
      srcdoc:contentCss,
      contentValue:''
    }
  },
  methods:{
    displayPreview(){
      this.srcdoc=`<!DOCTYPE html>
        <html lang="zh">
        <head>
        <title></title>
        <base href="http://localhost:2333/">
        <link type="text/css" rel="stylesheet" href="./tinymce/skins/ui/oxide/content.min.css">
        <link type="text/css" rel="stylesheet" href="./tinymce/skins/content/default/content.css">
        <style>
            ${contentCss}
        </style>
        </head>
        <body id="tinymce" class="mce-content-body ">
        ${this.contentValue}
        <script>
        document.addEventListener && document.addEventListener("click", function(e) {for (var elm = e.target; elm; elm = elm.parentNode) {if (elm.nodeName === "A" && !(e.ctrlKey && !e.altKey)) {e.preventDefault();}}}, false);
        </scr`+`ipt>
        </body>
        </html>`;
    },
    setup(editor) {
      console.log(editor)
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
